import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import {
  Card,
  Space,
  Button,
  Table,
  TableColumnProps,
  Message,
} from '@arco-design/web-react';
import {
  getCampusAiModelPage,
  setCampusAiModelPublish,
  cancelCampusAiModelPublish,
} from '@/api/model';
import {
  bottomMoldTypeOpt,
  modelStatusOptions,
} from '@/pages/resources/common';
import Search from '@/pages/resources/model/components/search';

function Model() {
  const history = useHistory();

  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  const [pagination, setPagination] = useState({
    showTotal: true,
    total: 0,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });

  const [searchParams, setSearchParams] = useState({
    QueryParam: {
      ModelNum: '', //模型编号
      ModelName: '', //模型名称
      BottomMoldTypes: null, //底膜类型
      UserName: '', //子账号名称
    },
    PageIndex: 1,
    PageSize: 10,
  });

  const onSearch = useCallback(
    (values) => {
      const params = {
        QueryParam: {
          ModelNum: values.ModelNum, //模型编号
          ModelName: values.ModelName, //模型名称
          BottomMoldTypes: values.BottomMoldTypes, //底膜类型
          UserName: values.UserName, //子账号名称
        },
        PageIndex: 1,
        PageSize: 10,
      };
      pagination.current = 1;

      pagination.current = 1;

      setSearchParams(params);
      getModelList(params);
    },
    [searchParams]
  );

  const onChangeTable = useCallback(
    (pagination) => {
      const { current, pageSize } = pagination;
      const obj = {
        PageIndex: current,
        PageSize: pageSize,
      };
      const newObj = Object.assign(searchParams, obj);
      getModelList(newObj);
      setSearchParams(newObj);
    },
    [searchParams]
  );

  const toModelDetails = (record) => {
    history.push({
      pathname: '/resources/modelDetails',
      search: `?ID=${record.ID}`,
    });
  };

  const publishModel = async (row) => {
    const res: any = await setCampusAiModelPublish({ ID: row.ID });
    if (res.StatusCode === 200) {
      Message.success(res.Message);
      getModelList();
    } else {
      Message.error(res.Message);
    }
  };
  const cancelPublishModel = async (row) => {
    const res: any = await cancelCampusAiModelPublish({ ID: row.ID });
    if (res.StatusCode === 200) {
      Message.success(res.Message);
      getModelList();
    } else {
      Message.error(res.Message);
    }
  };

  const columns: TableColumnProps[] = [
    {
      title: '序号',
      align: 'center',
      render: (col, record: any, index: number) => index + 1,
    },
    {
      title: '模型编号',
      dataIndex: 'ModelNum',
      align: 'center',
    },
    {
      title: '模型名称',
      dataIndex: 'ModelName',
      align: 'center',
    },
    {
      title: '底模类型',
      dataIndex: 'BottomMoldType',
      align: 'center',
      render: (col, record: any, index: number) => {
        return bottomMoldTypeOpt.find((item) => item.value == col)?.label;
      },
    },
    {
      title: '校园账号',
      dataIndex: 'UserName',
      align: 'center',
    },
    {
      title: '模型状态',
      dataIndex: 'Status',
      align: 'center',
      render: (col, record: any, index: number) => {
        return modelStatusOptions.find((item) => item.value == col)?.label;
      },
    },
    {
      title: '操作',
      dataIndex: 'undefined',
      align: 'center',
      fixed: 'right',
      width: 120,
      render: (col, record: any, index: number) => (
        <Space>
          {record.Status === 3 && (
            <Button type="text" onClick={() => publishModel(record)}>
              上架
            </Button>
          )}

          {record.Status === 2 && (
            <Button type="text" onClick={() => cancelPublishModel(record)}>
              下架
            </Button>
          )}

          <Button type="text" onClick={() => toModelDetails(record)}>
            查看
          </Button>
        </Space>
      ),
    },
  ];

  const getModelList = useCallback(
    async (params = {}) => {
      const reqData = {
        ...searchParams,
        ...params,
      };
      let res;
      setLoading(true);
      res = await getCampusAiModelPage(reqData);

      setPagination({
        ...pagination,
        total: res.Result.TotalCount,
        current: searchParams.PageIndex ? searchParams.PageIndex : 1,
      });

      setLoading(false);
      if (res.StatusCode === 200) {
        setData(res.Result.Datas);
      } else {
        Message.error('列表获取失败，请刷新重试');
      }
    },
    [searchParams]
  );

  useEffect(() => {
    getModelList();
  }, []);

  return (
    <div>
      <Card>
        <Search onSearch={onSearch}></Search>
      </Card>

      <Card style={{ marginTop: '20px' }}>
        <Table
          border
          rowKey="ID"
          borderCell
          columns={columns}
          data={data}
          pagination={pagination}
          loading={loading}
          onChange={onChangeTable}
        ></Table>
      </Card>
    </div>
  );
}

export default Model;
